package pro.syg.servlet;

import org.apache.commons.lang3.RandomStringUtils;
import pro.syg.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet(urlPatterns = "/syggoods/save")
@MultipartConfig(
        //上传的文件保存的具体位置
        location="D:\\Download\\IDEA\\upload-images",
        //最大支持的文件上限
        maxFileSize = 100*1024*1024,
        //最大支持的请求上限，要求 maxRequestSize>=maxFileSize
        maxRequestSize =104857600
)
public class GoodsSaveServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name =request.getParameter("n");
        String price = request.getParameter("");
        //获取来自前端提交的图片文件
        Part image = request.getPart("i");
        //获取来自前端提交的图片的原始名称
        String fileName = image.getSubmittedFileName();
        //将名称以.进行切割
        String[] strings = fileName.split("\\.");
        //获取文件的后缀名
        String suffix=strings[1];
        //为上传的图片设置新名称
        String img = RandomStringUtils.randomAlphabetic(10) + "." + suffix;
        //将提交的图片文件保存到磁盘
        image.write(img);

        String sql="insert into goods(`name`,price,image) values(?,?,?)";
        JdbcUtils.modify(sql,name,price,img);
        response.sendRedirect("/wyn/goods-list.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

